package com.woochen.baselibrary.navigation.top

import android.app.Activity
import android.content.Context
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView


/**
 * 创建人：chenwuchao
 * 创建时间：2017/5/17 18:57
 */
abstract class AbsNavigationBar<P : AbsNavigationBar.Builder.NavigationParams>(protected val params: P?) : INavigation {
    private var navigationView: View? = null

    init {
        createAndBindView()
    }

    protected fun getString(id: Int): String {
        return this.params!!.context.resources.getString(id)
    }

    protected fun getColor(id: Int): Int {
        return ContextCompat.getColor(this.params!!.context, id)
    }


    /**
     * 创建和绑定视图
     */
    private fun createAndBindView() {
        if (params!!.parent == null) {
            //获取activity的根布局  View的源码得到
            val activityRoot = (params.context as Activity).window.decorView as ViewGroup
            params.parent = activityRoot.getChildAt(0) as ViewGroup
        }

        if (params == null) {
            return
        }
        //1.创建View
        navigationView = LayoutInflater.from(params.context).inflate(bindLayoutId(), params.parent, false)
        //2.加入布局
        params.parent!!.addView(navigationView, 0)
        //3.绑定view
        applyView()
    }

    /**
     * 通过资源id找到布局
     * @param viewId
     */
    protected fun <T : View> findViewById(viewId: Int): T? {
        return navigationView!!.findViewById<View>(viewId) as T
    }

    /**
     * 设置文本
     * @param viewId
     * @param text
     */
    protected fun setText(viewId: Int, text: CharSequence) {
        val tv = findViewById<TextView>(viewId)
        if (tv != null) {
            tv.text = text
        }
    }

    /**
     * 设置点击事件
     * @param viewId
     * @param listener
     */
    protected fun setOnClickListener(viewId: Int, listener: View.OnClickListener) {
        val view = findViewById<View>(viewId)
        view?.setOnClickListener(listener)
    }


    /**
     * 设置背景资源
     * @param viewId
     * @param resourceId
     */
    protected fun setImageResource(viewId: Int, resourceId: Int) {
        val imageView = findViewById<ImageView>(viewId)
        imageView?.setImageResource(resourceId)
    }


    abstract class Builder {
        var P: NavigationParams
        abstract fun <T : AbsNavigationBar<*>> build(): T

        constructor(context: Context, parent: ViewGroup) {
            P = NavigationParams(context, parent)
        }

        constructor(context: Context) {
            P = NavigationParams(context, null)
        }

        // 默认的配置参数
        class NavigationParams(var context: Context, var parent: ViewGroup?)
    }

}
